//
//  ZMOcHelper.m
//  TravelForDriver
//
//  Created by Rowling on 2020/9/11.
//  Copyright © 2020 智蚂优服. All rights reserved.
//

#import "ZMOcHelper.h"
#import <AVFoundation/AVFoundation.h>
#import "SGDialog.h"
#import <CommonCrypto/CommonCrypto.h>
@implementation ZMOcHelper

#pragma mark - 生成渐变色图片
+ (UIImage *)createImageWithSize:(CGSize)imageSize gradientColors:(NSArray *)colors percentage:(NSArray *)percents gradientType:(GradientType)gradientType {
    NSAssert(percents.count <= 5, @"输入颜色数量过多，如果需求数量过大，请修改locations[]数组的个数");
    NSMutableArray *ar = [NSMutableArray array];
    for(UIColor *c in colors) {
        [ar addObject:(id)c.CGColor];
    }
    
    CGFloat locations[5];
    for (int i = 0; i < percents.count; i++) {
        locations[i] = [percents[i] floatValue];
    }
    
    UIGraphicsBeginImageContextWithOptions(imageSize, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, locations);
    CGPoint start;
    CGPoint end;
    switch (gradientType) {
        case GradientFromTopToBottom:
            start = CGPointMake(imageSize.width/2, 0.0);
            end = CGPointMake(imageSize.width/2, imageSize.height);
            break;
        case GradientFromLeftToRight:
            start = CGPointMake(0.0, imageSize.height/2);
            end = CGPointMake(imageSize.width, imageSize.height/2);
            break;
        case GradientFromLeftTopToRightBottom:
            start = CGPointMake(0.0, 0.0);
            end = CGPointMake(imageSize.width, imageSize.height);
            break;
        case GradientFromLeftBottomToRightTop:
            start = CGPointMake(0.0, imageSize.height);
            end = CGPointMake(imageSize.width, 0.0);
            break;
        default:
            break;
    }
    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}

+ (void)imageWihtSize:(UIImage *)image size:(CGSize)size radius:(CGFloat)radius backColor:(UIColor *)backColor completion:(void(^)(UIImage *image))completion {
        // 异步绘制裁切
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 利用绘图建立上下文
        UIGraphicsBeginImageContextWithOptions(size, true, 0);
        CGRect rect = CGRectMake(0, 0, size.width, size.height);
        // 填充颜色
        [backColor setFill];
        UIRectFill(rect);
        // 贝塞尔裁切
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius];
        [path addClip];
        [image drawInRect:rect];
          
        // 获取结果
        UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
        // 关闭上下文
        UIGraphicsEndImageContext();
        // 主队列回调
        dispatch_async(dispatch_get_main_queue(), ^{
        completion(resultImage);
        });
        });
}

+(BOOL)isNull:(id)value {
    if (!value) return YES;
    if ([value isKindOfClass:[NSNull class]]) return YES;

    return NO;
}

//对返回的数据进行区分筛选
+ (NSMutableArray *)groupAction2:(NSMutableArray *)arr {
    NSArray *serviceTypes = [arr valueForKeyPath:@"@distinctUnionOfObjects.merchantId"];
    NSArray *sortDesc = @[[[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES]];
    NSArray *sortSetArray = [serviceTypes sortedArrayUsingDescriptors:sortDesc];
    __block NSMutableArray *groupArr = [NSMutableArray array];
    [sortSetArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"merchantId = %@", obj];
        NSArray *tempArr = [NSArray arrayWithArray:[arr filteredArrayUsingPredicate:predicate]];
        [groupArr addObject:tempArr];
    }];
    return groupArr;
}

#pragma -mark:通过一个View将其内容生成图片
+(UIImage *)imageWithCaputureView:(UIView *)view{
    // 开启位图上下文
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
    // 获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    // 把控件上的图层渲染到上下文,layer只能渲染
    [view.layer renderInContext:ctx];
    // 生成一张图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭上下文
    UIGraphicsEndImageContext();
    return image;
}

+ (void)VideoTranstoMP4:(NSURL *)Url{
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:Url options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    __block NSData *data = [NSData new];
    if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]){
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:date];
        NSString *exportPath = [NSString stringWithFormat:@"%@/%@.mp4", [NSHomeDirectory() stringByAppendingString:@"/tmp"], dateString];
        exportSession.outputURL = [NSURL fileURLWithPath:exportPath];
        exportSession.outputFileType = AVFileTypeMPEG4;
        dispatch_semaphore_t wait = dispatch_semaphore_create(0l);
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed:
                    [SGDialog showWeakStr:@"转码失败" withImg:@""];
                    break;
                case AVAssetExportSessionStatusCancelled:
                    [SGDialog showWeakStr:@"转码失败" withImg:@""];
                    break;
                case AVAssetExportSessionStatusCompleted:{
                    data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:exportPath]];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"VideoTransCodingSuccess" object:nil userInfo:@{@"videoData":data}];
                    });
                    [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
                }
                    break;
                default:
                    break;
            }
            dispatch_semaphore_signal(wait);
        }];
        long timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
        if (timeout) {
            NSLog(@"timeout.");
        }
        if (wait) {
            wait = nil;
        }
    }
}

+ (UIImage *)getScreenShotImageFromVideoURL:(NSString *)fileurl{
    UIImage *shotImage;
    NSURL *fileURL = [NSURL URLWithString:fileurl];
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:fileURL options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    shotImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return shotImage;
}

// 加密方法
+ (NSString*)encrypt:(NSString*)plainText key:(NSString *)key{
    NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    size_t plainTextBufferSize = [data length];
    const void *vplainText = (const void *)[data bytes];
    
    CCCryptorStatus ccStatus;
    uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;
    
    bufferPtrSize = 2048;
    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
    memset((void *)bufferPtr, 0x0, bufferPtrSize);
    
    const void *vkey = (const void *) [key UTF8String];
    const void *vinitVec = (const void *) [key UTF8String];
    
    ccStatus = CCCrypt(kCCEncrypt,
                       kCCAlgorithmAES,
                       kCCOptionPKCS7Padding,
                       vkey,
                       kCCKeySizeAES128,
                       vinitVec,
                       vplainText,
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       bufferPtrSize,
                       &movedBytes);
    NSString * ciphertext = @"";
    if (ccStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytes:bufferPtr length:(NSUInteger)movedBytes];
        NSData * S64tring = [data base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
        ciphertext = [[NSString alloc] initWithData:S64tring encoding:kCFStringEncodingUTF8];
    }
    free(bufferPtr);
    return ciphertext;
}

// 解密方法
+ (NSString*)decrypt:(NSString*)encryptText key:(NSString *)key{
    NSData * base64Data = [encryptText dataUsingEncoding:kCFStringEncodingUTF8];
    if (base64Data == nil) {return @"";}
    NSData *encryptData = [[NSData alloc] initWithBase64EncodedData:base64Data options:NSDataBase64DecodingIgnoreUnknownCharacters]; //[self hexStringToData:encryptText];//[GTMBase64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];
    size_t plainTextBufferSize = [encryptData length];
    const void *vplainText = [encryptData bytes];

    CCCryptorStatus ccStatus;
    uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;
    bufferPtrSize = 2048;
    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
    memset((void *)bufferPtr, 0x0, bufferPtrSize);
    const void *vkey = (const void *) [key UTF8String];
    const void *vinitVec = (const void *) [key UTF8String];

    ccStatus = CCCrypt(kCCDecrypt,
                       kCCAlgorithmAES,
                       kCCOptionPKCS7Padding,
                       vkey,
                       kCCKeySizeAES128,
                       vinitVec,
                       vplainText,
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       bufferPtrSize,
                       &movedBytes);

    NSString *result = @"";
    if (ccStatus == kCCSuccess) {
       result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr
                                                              length:(NSUInteger)movedBytes] encoding:NSUTF8StringEncoding];
    }
    free(bufferPtr);
    return result;
}

@end
